import json

from flask import render_template,request,jsonify
from . import servers

import os
from frameworks.cores.Config import *
from frameworks.utils.JsonResult2 import *
from frameworks.cores.LoadClass import *
from frameworks.utils.RedisUtil import *

basepath = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
config = Config(basepath)

apimap = config.getApi()
env = apimap["base"]
print(env)
from flask_session import Session

jsonResult = JsonResult2()

loader = LoadClass()
redis = RedisUtil()

@servers.route(env+"/aacharts",methods=['GET'])
def aacharts():
    ck = request.args.get("ck","")
    al = redis.vget(ck)
    if al == None:
        return jsonResult.setOk([], "获取成功")
    else:
        print("=======read cache===============")
        return jsonResult.setOk(al, "获取成功")

@servers.route('/server_monitor/list')
def server_monitor_list():
    hostData = loader.load("controller.servers.ServerController", "ServerController", {
        "func": "getAllData",
        "fields": ["id", "server_name", "ip"],
    })
    return render_template(
        'servers/server_monitor_list.html',
        hostData=hostData
    )

@servers.route(env+"/server_monitor/cols",methods=['GET','POST'])
def server_monitor_cols():
    rs = loader.load("controller.servers.ServerMonitorController", "ServerMonitorController", {
        "func":"getColumns",
        "fields":["id","server_id","cpu","mem","disk","ctime","mtime"]
    })
    return jsonResult.setOk(rs,"获取成功")

@servers.route(env+"/server_monitor/page",methods=['GET'])
def server_monitor_page():
    num = request.args.get("limit",10)
    page = request.args.get("page",1)
    data = loader.load("controller.servers.ServerMonitorController", "ServerMonitorController", {
        "func": "getData",
        "fields": ["id","server_id","cpu","mem","disk","ctime","mtime"],
        "page": page,
        "num": num,
        "orderfield": "id",
        "asc": "asc"
    })
    return json.dumps(data)